import axios from 'axios'
import {  Message } from 'element-ui'
import global_ from '../components/global/global.vue'
// 创造一个请求

const service = axios.create({
  baseURL: global_.BASE_URL, // url = base url + request url
  timeout: 10000000000 // 设置延迟
})
//这个配置是是否让axios请求的时候带上Cookice
axios.defaults.withCredentials = true;
// 拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前设置头部
    let token = localStorage.getItem('token')
    let refreshToken = localStorage.getItem('refreshToken')
    if (token) {
      config.headers['Token'] = token
      config.headers['refreshToken'] = refreshToken
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.success) {
    } else {
      if (res.code ===10003) {
        Message({
          message: '登录过期，请重新登录',
          type: 'warning'
        })
        //清除缓存
        localStorage.clear()
        setTimeout(() => {
          window.location.reload()
        }, 500)
      } else if (!res.success) {
        Message({
          message: res.message,
          type: 'warning'
        })
      }
    }
    return res
  },
  error => {
    //console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'warning',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
